package com.qd.panda.service.wallet.publish;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.domain.entity.wallet.publish.PlanPublishListDTO;
import com.qd.panda.mapper.wallet.publish.PlanPublishListMapper;
import com.qd.panda.model.Plan;
import com.qd.panda.model.PlanPublishList;
import com.qd.panda.service.wallet.user.UserWalletRechargeLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * 套餐列表
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class PlanPublishListService extends BaseService<PlanPublishListMapper, PlanPublishList> {

    private static final String PREFIX_ID = "panda_plan_publish_list_publishListId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_PLAN = "panda_plan_publish_list_publishId_{0}_planCode_{1}";
    private static final String PREFIX_LIST = "panda_plan_publish_list_publishId_{0}";

    private final RedisTemplateUtil<PlanPublishList> redisTemplateUtil;
    private final com.qd.panda.service.wallet.plan.PlanService planService;
    private final UserWalletRechargeLogService userWalletRechargeLogService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PlanPublishListDTO save(PlanPublishListDTO dto) {
        checkUnique(dto);
        final PlanPublishList model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PlanPublishListDTO update(PlanPublishListDTO dto) {
        checkUnique(dto);
        final PlanPublishList historyModel = Optional.ofNullable(getById(dto.getPublishListId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final PlanPublishList model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<PlanPublishList> mList) {
        for (PlanPublishList planPublishList : mList) {
            Plan plan = planService.getById(planPublishList.getPlanCode());
            if (null == plan) {
                throw new ApiException("套餐编码值错误:[" + planPublishList.getPlanCode() + "]");
            }
            if (plan.getEnable().equals(ConstantDto.SF0)) {
                throw new ApiException("套餐已经停用:[" + planPublishList.getPlanCode() + "]");
            }
        }
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<PlanPublishList> mList) {
        final List<String> ids = mList.stream().map(PlanPublishList::getPublishListId).collect(toList());
        final List<PlanPublishList> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param publishListId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String publishListId) {
        final PlanPublishList historyModel = Optional.ofNullable(getById(publishListId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        if(userWalletRechargeLogService.existsByPlanCode(historyModel.getPlanCode())){
            throw new ApiException("已经存在订购信息不能删除");
        }
        try {
            if (!super.removeById(publishListId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
      ids.forEach(this::removeById);
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(PlanPublishListDTO dto) {
        final QueryWrapper<PlanPublishList> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param publishListId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String publishListId) {
        boolean exists = false;
        if (StringUtils.hasLength(publishListId)) {
            final PlanPublishList model = getById(publishListId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param publishListId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public PlanPublishList getById(String publishListId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, publishListId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(publishListId), PlanPublishList.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param publishListId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PlanPublishListDTO getByIdDto(String publishListId) {
        return Optional.ofNullable(getById(publishListId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public PlanPublishList getOne(PlanPublishListDTO dto) {
        final QueryWrapper<PlanPublishList> queryWrapper = createQueryWrapper(dto);
        PlanPublishList model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PlanPublishListDTO getOneDto(PlanPublishListDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<PlanPublishList> getList(PlanPublishListDTO dto) {
        final QueryWrapper<PlanPublishList> queryWrapper = createQueryWrapper(dto);
        final List<PlanPublishList> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<PlanPublishListDTO> getListDto(PlanPublishListDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<PlanPublishListDTO> page(Page<PlanPublishList> page, PlanPublishListDTO dto) {
        final QueryWrapper<PlanPublishList> queryWrapper = createQueryWrapper(dto);
        Page<PlanPublishList> iPage = baseMapper.selectPage(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(this::modelToDtoList);
        queryWrapper.clear();
        return iPage.convert(this::modelToDto);
    }

    /**
     * 根据唯一性索引获得数据
     * param publishId
     * param planCode
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public PlanPublishList getUniqueByPublishIdAndPlanCode(String publishId, String planCode) {
        final QueryWrapper<PlanPublishList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publish_id", publishId);
        queryWrapper.eq("plan_code", planCode);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_PLAN, publishId, planCode);
        final PlanPublishList model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), PlanPublishList.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    @Transactional(readOnly = true)
    public void checkUnique(PlanPublishListDTO dto) {
        PlanPublishList model = getUniqueByPublishIdAndPlanCode(dto.getPublishId(), dto.getPlanCode());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(PlanPublishListDTO dto, PlanPublishList model) {
        if (!StringUtils.hasLength(dto.getPublishListId())) {
            throw new ApiException("数据已存在，请勿重复操作");
        }
        if (!dto.getPublishListId().equals(model.getPublishListId())) {
            throw new ApiException("数据已存在，请勿重复操作");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(PlanPublishList model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPublishListId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_PLAN, model.getPublishId(), model.getPlanCode()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getPublishId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<PlanPublishList> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPublishListId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        Set<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_PLAN, model.getPublishId(), model.getPlanCode())).collect(toSet());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
        Set<String> publishIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, model.getPublishId())).collect(toSet());
        if (!publishIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(publishIds);
            publishIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public PlanPublishListDTO modelToDto(PlanPublishList model) {
        if (null == model) {
            return null;
        }
        final PlanPublishListDTO dto = new PlanPublishListDTO();
        dto.setPublishListId(model.getPublishListId());
        dto.setIdx(model.getIdx());
        dto.setPublishId(model.getPublishId());
        dto.setPlanCode(model.getPlanCode());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public PlanPublishList dtoToModel(PlanPublishListDTO dto) {
        if (null == dto) {
            return null;
        }
        final PlanPublishList model = new PlanPublishList();
        model.setPublishListId(dto.getPublishListId());
        model.setIdx(dto.getIdx());
        model.setPublishId(dto.getPublishId());
        model.setPlanCode(dto.getPlanCode());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(PlanPublishListDTO dto) {
        dto.setPlanDTO(planService.getByIdDto(dto.getPlanCode()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<PlanPublishListDTO> modelToDtoList(List<PlanPublishList> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<PlanPublishList> dtoToModelList(List<PlanPublishListDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<PlanPublishList> createQueryWrapper(PlanPublishListDTO dto) {
        final QueryWrapper<PlanPublishList> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(dto.getPublishId())) {
                queryWrapper.eq("publish_id", dto.getPublishId());
            }
            if (StringUtils.hasLength(dto.getPlanCode())) {
                queryWrapper.eq("plan_code", dto.getPlanCode());
            }
        }
        queryWrapper.orderByAsc("idx");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<PlanPublishList> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<PlanPublishList> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(PlanPublishList::getPublishListId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(readOnly = true)
    public List<PlanPublishListDTO> getListByPublishIdDTO(String publishId) {
        return modelToDtoList(getListByPublishId(publishId));
    }

    @Transactional(readOnly = true)
    public List<PlanPublishList> getListByPublishId(String publishId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_LIST, publishId);
        return redisTemplateUtil.getList(new CacheKey().setKey(key), () -> {
            final QueryWrapper<PlanPublishList> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("publish_id", publishId);
            queryWrapper.orderByAsc("idx");
            List<PlanPublishList> list = super.list(queryWrapper);
            queryWrapper.clear();
            return list;
        }, PlanPublishList.class);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByPublishId(String publishId) {
        List<PlanPublishList> list = getListByPublishId(publishId);
        if (!list.isEmpty()) {
            List<String> ids = list.stream().map(PlanPublishList::getPublishListId).collect(toList());
            removeBatchIds(ids);
        }
    }

    @Transactional(readOnly = true)
    public boolean isExistsByPlanCode(String planCode) {
        final QueryWrapper<PlanPublishList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_code", planCode);
        boolean exists = getBaseMapper().exists(queryWrapper);
        queryWrapper.clear();
        return exists;
    }
}